package com.magicsoft.share.base;

import android.content.Context;
import android.view.View;

import java.lang.ref.WeakReference;

import io.reactivex.disposables.CompositeDisposable;

/**
 * Created by lyf on 2017/8/16.
 */

public abstract class BasePresenter<T extends BaseView> {
    protected Context mContext;
    //View的弱引用
    protected WeakReference<T> mWeakReference;
    protected CompositeDisposable mCompositeDisposable = new CompositeDisposable();


    public void onDestroy() {
        cancelNetWork();
    }

    public void cancelNetWork() {
        if (mCompositeDisposable != null) {
            mCompositeDisposable.dispose();
        }
    }


    /**
     * 注入view.
     */
    public void attach(T mView) {
        mWeakReference=new WeakReference<T>(mView);
        getContext();
    }

    /**
     * 销毁操作
     */
    public void detach() {
        if (mWeakReference != null) {
            mWeakReference.clear();
        }
    }

    protected T getView() {
        return mWeakReference.get();
    }

    /**
     * 获取context.
     */
    public void getContext() {
        if (getView() instanceof BaseActivity) {
            mContext = (Context) getView();
        } else if (getView() instanceof BaseFragment) {
            mContext = ((BaseFragment) getView()).getActivity();
        } else if (getView() instanceof View) {
            mContext = ((View) getView()).getContext();
        } else {
            throw new IllegalArgumentException("view must instanceof activity or fragment");
        }
    }


}
